package utils;

import java.sql.*;
import java.util.HashMap;
import java.util.Map;

public class DBUtils {
    //连接数据库连接对象
    public static Connection getConn() throws ClassNotFoundException, SQLException {
        //加载驱动
        Class.forName("com.mysql.jdbc.Driver");
        //获取连接对象
        String url = "jdbc:mysql://localhost:3306/books";
        return DriverManager.getConnection(url,"root","mysql");
    }
    //释放资源
    public static void close(Connection conn){
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    public static void close(ResultSet rs){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    public static void close(Statement st){
        if(st!=null){
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    public static void close(ResultSet re,Statement st,Connection conn){
        try {
            re.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            st.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    //查询一条数据
    public static Map<String,Object> getOne(String sql) throws SQLException, ClassNotFoundException {
        Map<String,Object> result=new HashMap<>();
        Connection conn=getConn();
        PreparedStatement ps= conn.prepareStatement(sql);
        ResultSet rs=ps.executeQuery();
        if(rs.next()){
            ResultSetMetaData metaData= rs.getMetaData();
            for(int i=1;i<=metaData.getColumnCount();i++){
                String col=metaData.getColumnLabel(i);
                Object value=rs.getObject(i);
                result.put(col,value);
            }
        }
        return result;
    }
    //封装执行sql语句
    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        Map<String,Object> map=getOne("select id,title,`read` from t_book where id=1");
        System.out.println(map);
    }
}
